﻿using System;
using System.Windows.Forms;
using Office = Microsoft.Office.Core;
using GalaSoft.MvvmLight.Messaging;

namespace Songhay.Office2010.WordWalkingStick
{
    using Properties;
    using Songhay.Wpf.WordWalkingStick;

    /// <summary>
    /// Office Word Add-In
    /// </summary>
    public partial class ThisAddIn
    {
        /// <summary>
        /// Returns an object that implements the Microsoft.Office.Core.IRibbonExtensibility interface.
        /// </summary>
        /// <returns>
        /// An object that implements the Microsoft.Office.Core.IRibbonExtensibility interface.
        /// </returns>
        /// <remarks>
        /// Follow these steps to enable the Ribbon (XML) item:
        /// 1: Copy the following code block into the ThisAddin, ThisWorkbook, or ThisDocument class.
        ///
        /// This member runs before the Startup Event.
        /// </remarks>
        protected override Microsoft.Office.Core.IRibbonExtensibility CreateRibbonExtensibilityObject()
        {
            var ribbon = new WordRibbon();
            return ribbon;
        }

        void ThisAddIn_Startup(object sender, System.EventArgs e)
        {
            this._mef = WordWalkingStickCompositionHost.MefHost;
            this._mef.WordApplication = this.Application;
            this._mef.Compose(Settings.Default.CompositionVstoCommandsPath,
                Settings.Default.CompositionOpenXmlTransformPath);


            //Send MvvmLight message:
            var message = new GenericMessage<WordWalkingStickCompositionHost>(this._mef);
            Messenger.Default.Send(message);

            AppDomain.CurrentDomain.UnhandledException += (s, args) =>
            {
                if(!args.IsTerminating)
                {
                    Exception ex = (Exception)args.ExceptionObject;
                    MessageBox.Show(ex.Message, "Songhay Add-In",
                        MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            };
#if DEBUG
            System.Diagnostics.Debug.WriteLine("ThisAddIn_Startup");
#endif
        }

        void ThisAddIn_Shutdown(object sender, System.EventArgs e)
        {
            if(this._mef != null) this._mef.Dispose();
#if DEBUG
            System.Diagnostics.Debug.WriteLine("ThisAddIn_Shutdown");
#endif
        }

        WordWalkingStickCompositionHost _mef;

        #region VSTO generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InternalStartup()
        {
            this.Startup += new System.EventHandler(ThisAddIn_Startup);
            this.Shutdown += new System.EventHandler(ThisAddIn_Shutdown);
        }

        #endregion
    }
}
